package com.stedu.mall.userservice.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageInfo;
import com.stedu.mall.common.bean.RespBean;
import com.stedu.mall.common.bean.User;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.UserService;
import com.stedu.mall.common.utils.JwtUtil;
import com.stedu.mall.common.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;

    @GetMapping("/captcha")
    public RespBean captcha() {
        //创建验证码对象
        LineCaptcha captcha = new LineCaptcha(120, 32, 5, 10);
        //生成唯一的key
        String key = IdUtil.getSnowflakeNextIdStr();
        //将key和验证码文本保存在redis中
        redisUtil.set(key, captcha.getCode(), 60);
        //将验证码图片转换成Base64编码格式
        String imageBase64Data = captcha.getImageBase64Data();
        //将key和Base64编码保存在map中
        HashMap<String, Object> map = new HashMap<>();
        map.put("key", key);
        map.put("imageBase64Data", imageBase64Data);
        //将key和Base64图片返回
        return RespBean.ok("生成验证码成功", map);
    }

    @PostMapping("/login")
    public RespBean login(String username, String password, String key, String captchaInput) throws SteduException {
        //判断验证码是否正确
        String captcha = (String) redisUtil.get(key);
        if (captcha == null || !captcha.equalsIgnoreCase(captchaInput)) {
            throw new SteduException("验证码错误，请确认验证码");
        }
        //登录
        User user = userService.login(username, password);
        //生成token
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("username", user.getUsername());
        map.put("role", "user");
        String jwtStr = JwtUtil.generateJwt(map);
        //返回token给用户
        return RespBean.ok("登录成功", jwtStr);
    }

    @PutMapping("/updateLogin")
    public RespBean updateLogin(@RequestBody User user, @RequestHeader("token") String token) {
        //解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        user.setId(userId);

        if (userService.updateL(user)) {
            return RespBean.ok("修改成功");
        } else {
            return RespBean.error("修改失败");
        }
    }

    @PutMapping("/updatePay")
    public RespBean updatePay(@RequestBody User userP, @RequestHeader("token") String token) {
        //解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        User user = userService.selectById(userId);
        if (!user.getPassword().equals(SecureUtil.md5(SecureUtil.md5(userP.getPassword() + user.getSalt())))) {
            return RespBean.error("登录密码不正确");
        }
        userP.setId(userId);
        userP.setSalt(user.getSalt());
        if (userService.updateP(userP)) {
            return RespBean.ok("修改成功");
        } else {
            return RespBean.error("修改失败");
        }
    }

    //获取登录信息
    @GetMapping("/info")
    public RespBean getLogin(@RequestHeader("token") String token) {
        //解析token
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        //获取用户id - 根据id查询用户信息
        Integer id = (Integer) map.get("id");
        User user = userService.selectById(id);
        //返回
        return RespBean.ok("", user);
    }

    @PostMapping("/reg")
    public RespBean reg(String username, String password, String key, String captchaInput) throws SteduException {
        //判断验证码是否正确
        String captcha = (String) redisUtil.get(key);
        if (captcha == null || !captcha.equalsIgnoreCase(captchaInput)) {
            throw new SteduException("验证码错误，请确认验证码");
        }
        //设置用户信息
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //注册
        userService.reg(user);
        return RespBean.ok("注册成功");
    }

    @GetMapping
    public RespBean selectByAll(User user, Integer pageNum, Integer pageSize) {
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 5 : pageSize;
        PageInfo<User> userPageInfo = userService.selectByAll(user, pageNum, pageSize);

        return RespBean.ok("查询成功", userPageInfo);
    }

    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable Integer id) {
        User user = userService.selectById(id);
        return RespBean.ok("", user);
    }

    @GetMapping("/monkey")
    public RespBean selectByMonkey(@RequestHeader("token") String token) {
        //解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer id = (Integer) map.get("id");

        User user = userService.selectById(id);
        return RespBean.ok("", user);
    }

    @PutMapping("/{id}")
    public RespBean reset(@PathVariable Integer id) {
        User user = new User();
        user.setId(id);
        boolean reset = userService.reset(user);
        if (reset) {
            return RespBean.ok("重置密码成功 ");
        } else {
            return RespBean.error("重置密码失败");
        }
    }

    @PutMapping
    public RespBean update(@RequestBody User user) {
        boolean update = userService.update(user);
        if (update) {
            return RespBean.ok("修改成功 ");
        } else {
            return RespBean.error("修改失败");
        }
    }


    //充值
    @PutMapping("/updateMoney")
    public RespBean updateMoney(@RequestBody User user, @RequestHeader("token") String token) {
        //解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer id = (Integer) map.get("id");
        user.setId(id);

        boolean update = userService.updateInsert(user);
        if (update) {
            return RespBean.ok("充值成功 ");
        } else {
            return RespBean.error("充值失败");
        }
    }

    @PutMapping("/u")
    public RespBean updateU(@RequestBody User user, @RequestHeader("token") String token) throws SteduException {
        //解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        user.setId(userId);
        if (userService.updateU(user)) {
            return RespBean.ok("认证成功");
        } else {
            return RespBean.error("认证失败");
        }
    }

    @PutMapping("/update")
    public RespBean uUpdate(@RequestBody User user, @RequestHeader("token") String token) throws SteduException {
        //解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        user.setId(userId);

        if (userService.uUpdate(user)) {
            return RespBean.ok("修改成功");
        } else {
            return RespBean.error("修改失败");
        }
    }

    @GetMapping("/id")
    public RespBean selectId(@RequestHeader("token") String token) {
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        //获取用户id - 根据id查询用户信息
        Integer id = (Integer) map.get("id");

        User user = userService.selectById(id);

        return RespBean.ok("", user);
    }
}
